//
//  MLUserAccountViewModel.swift
//  MLWeiBo
//
//  Created by wenxing on 2017/1/7.
//  Copyright © 2017年 Se7venX. All rights reserved.
//

import UIKit


class MLUserAccountViewModel: NSObject {
    
    
    static let shared = MLUserAccountViewModel()
    
    //用户对象
    var userAccount:MLUserAccount?
    
    
    override init() {
        super.init()

        /// 从沙盒里取  下次程序启动就可以获取shuju l 
        userAccount = loadDataFromSanbox()
    }
    
    var isUserLogin:Bool {
    
        /// 用户信息存在，且 令牌没有过期
        if userAccount != nil && isOutDate == false {
        
            return true
        }
    
        return false
    }
    
    /// 是否过期
   private var isOutDate: Bool? {
    
        ///没有过期
        if  (userAccount?.expires_date?.compare(Date()) == .orderedDescending) {
            
            return false
        }
        
        return true
    }
    
    
    
    
    /*
     * 第二步：请求令牌：access_token
     */
    func loadAccess_Token(code:String,finished:@escaping (Bool)->()) {
        
        let urlString =  urlString_access_token
        
        let parameters = [
            "client_id":AppKey,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":App_redirect_uri]
        
        MLNetworkTool.shared.ml_requestData(method: .POST, url: urlString, parameters: parameters) { (objc, error) in
            
            if error != nil {
                
                print(error!)
                
                finished(false)
                return
            }
            
//            print(objc!)
            /*
             
             "access_token" = "2.00TmIoqCSkLREDbd11559e4buq7CcE";
             "expires_in" = 157679999;
             "remind_in" = 157679999;
             uid = 2612585293;
             
             */
            
            let dic:[String:Any] =  objc as! [String : Any]
            
            //            let userAccount = MLUserAccount(dic: objc as! [String : Any])
            
            self.loadUserInfo(dic: dic,finished: finished)
        }
    }
    
    /*
     * 第三步：获取个人信息
     */
    private func loadUserInfo(dic:[String:Any],finished:@escaping (Bool)->()) {
        let accesstoken = dic["access_token"] as! String
        let uid = dic["uid"] as! String
        
        let urlString = urlString_userInfo + "?access_token=" + accesstoken + "&uid=" + uid
        
        
        print(accesstoken,uid)
        
        //        let parameters = ["access_token":accesstoken,
        //                          "uid":uid]
        
        MLNetworkTool.shared.ml_requestData(method: .GET, url: urlString, parameters: nil, finishedClosure: { (objc,error) -> () in
            
            if error != nil {
                
                print(error!)
                
                finished(false)
                
                return
            }
            
            //合并
            var responseDic = objc as! [String : Any]
            
            for (key,value) in dic {
                
                responseDic[key] = value
            }
            

            let userAccount = MLUserAccount(dic: responseDic)
            
            /// 目的是为了从未登录进去welVC界面，找不到userAccount
            self.userAccount = userAccount;
            
            //归档
            self.saveDataToSanbox(userAccount: userAccount)
  
            //解档
            finished(true)
            
            
        })
    }
    
    
    private func saveDataToSanbox(userAccount:MLUserAccount){
    
        let urlString = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last)! as NSString
        let path =  urlString.appendingPathComponent("user.plist")
        
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
    }
    
    
    private func loadDataFromSanbox() -> MLUserAccount? {

        let urlString = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last)! as NSString
        let path =  urlString.appendingPathComponent("user.plist")
        
        let userAccount11 = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        
        if let user = userAccount11 as? MLUserAccount {
            
            return user
        }
    
        return nil;
    }
    

}
